#include "FTPServer.hpp"


FTPServer::FTPServer(io_context &io, uint16_t port)
:acceptor_(io,tcp::endpoint(boost::asio::ip::tcp::v4(),port))
{
    
    //初始化日志
    logger = spdlog::basic_logger_mt("ftpserverlog", "ftpserverlog.txt");
    logger = spdlog::stdout_color_mt("FTPServer");
    logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] %v");
    logger->info("ftpserverlog create successfully!");
    //设置套接字选项
    acceptor_.set_option(tcp::acceptor::reuse_address(true));
    logger->info("FTP server listening on port {}", port);
}

void FTPServer::Start()
{
    if (!acceptor_.is_open())
    {
        logger->error("Acceptor not open!");
        return;
    }
    logger->info("Start DoAccept!");
    DoAccept();
}

void FTPServer::DoAccept()
{
    acceptor_.async_accept(
        [this](boost::system::error_code ec, tcp::socket socket)
        {
            if (!ec)
            {
                // 在移动socket之前获取远程端点
                std::string remote_address;
                try
                {
                    remote_address = socket.remote_endpoint().address().to_string();
                }
                catch (const std::exception &e)
                {
                    logger->error("Failed to get remote endpoint: {}", e.what());
                    // 继续接受新连接
                    DoAccept();
                    return;
                }

                auto session = std::make_shared<Session>(std::move(socket));
                sessions_.emplace_back(session);
                session->Start();
                logger->info("New connection from {}", remote_address);
            }
            else
            {
                logger->error("Accept error: {}", ec.message());
            }

            // 继续接受新连接
            DoAccept();
        });
}
